//
//  HWHomeNewRecommendViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/7.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView

private let headerID    = "HWNewRecommendTopView"

class HWHomeNewRecommendViewController: HWBaseViewController {

    var httpManager = HWHomeHttpManager()
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(HWNewGongNengView.self, HWNewRecommendGameView.self, HWNewHotGameView.self,HWNewDiscoverMoreView.self)
        tableView.register(HWHomeTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        return tableView
    }()
    private var pageIndex = 1
    private var topView = HWHomeInfoTopView()
    private var dataModel: HWNewHomeModel?
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = "#F7F8FA".toColor
        view.subviews{
            tableView
        }
        
        loadData()
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        tableView.fillContainer()
        
        topView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 170*widthScale)
        tableView.tableHeaderView = topView
        addRefresh()
        
        //========noti==========
        NotificationCenter.default.addObserver(self, selector: #selector(toDetailVc), name: .newGameTopToDetailVC, object: nil)
    }
    
    @objc private func toDetailVc(noti: Notification) {
        
        if let infoId = noti.userInfo?["infoID"] as? Int {
            if infoId == 584 {
                //黑神话
                self.navigationController?.pushViewController(HWWuKongDetailVC(), animated: true)
            }else{
                //其他游戏详情
                pushToDetailVC(infoId: infoId)
            }
            
        }
    }

    private func pushToDetailVC(infoId: Int){
        
        let detailVC = HWGameDetailController()
        detailVC.gameId = String(infoId)
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}

//MARK: - loadData
extension HWHomeNewRecommendViewController {

    private func loadData(){
        tableView.mj_footer?.endRefreshing()
        httpManager.getNewHomeRecommend(p: pageIndex) { model in
            self.tableView.mj_header?.endRefreshing()
            self.dataModel = model
            self.topView.bannarModel = model.slide
            self.tableView.reloadData()
        } failure: { err in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }

    }
    
    private func addRefresh() {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    @objc private func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc private func loadMoreData() -> () {
        pageIndex += 1
        
        httpManager.getNewHomeRecommend(p: pageIndex) { model in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if (model.data?.count ?? 0) > 0 {
                for mod in (model.data)! {
                    self.dataModel?.data?.append(mod)
                }
            } else {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}


//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWHomeNewRecommendViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 4 {
            return dataModel?.data?.count ?? 0
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWNewGongNengView", for: indexPath) as! HWNewGongNengView
            cell.sourceData = dataModel?.gongneng
            cell.rankArray = dataModel?.newgame_top
            cell.clickCateBlock = { type in
                if type.count > 0{
                    HWUniversal.pushController(type: type, urlString: "")
                }else{
                    let loginController = HWLoginController()
                    self.navigationController?.pushViewController(loginController, animated: true)
                }
            }
            return cell
        } else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWNewRecommendGameView", for: indexPath) as! HWNewRecommendGameView
            cell.dataSource = dataModel?.tuijian
            return cell
        } else if indexPath.section == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWNewHotGameView", for: indexPath) as! HWNewHotGameView
            cell.dataSource = dataModel?.remen
            return cell
        } else if indexPath.section == 3{
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWNewRecommendGameView", for: indexPath) as! HWNewRecommendGameView
            cell.dataSource = dataModel?.newgame_later
            return cell
        } else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWNewDiscoverMoreView", for: indexPath) as! HWNewDiscoverMoreView
            cell.model = dataModel?.data?[indexPath.row]
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 4 {
            let infoId = dataModel?.data?[indexPath.row].id ?? 0
            pushToDetailVC(infoId: infoId)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 440*widthScale
        }else if indexPath.section == 1 {
            return 255*widthScale
        }else if indexPath.section == 2 {
            return 196*widthScale
        }else if indexPath.section == 3 {
            return 255*widthScale
        }else{
            return 272*widthScale
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! HWHomeTitleHeaderView
        if section == 1 {
            header.titleString = "小编推荐"
        }else if section == 2 {
            header.titleString = "热门推荐"
        }else if section == 3 {
            header.titleString = "近期新游"
        }else if section == 4 {
            header.titleString = "探索更多"
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            return 0
        }        
        return 46*widthScale
    }
}

extension HWHomeNewRecommendViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
